<template>
  <div class="user-manage">
    <el-container>
      <el-main>
        <div class="page-header">
          <h1>用户管理</h1>
        </div>

        <el-card>
          <div class="toolbar">
            <el-input
              v-model="keyword"
              placeholder="搜索用户名/邮箱"
              style="max-width: 260px"
              clearable
            />
            <el-button type="primary" @click="loadUsers">搜索</el-button>
            <el-button :disabled="!selected.length" @click="batchEnable">批量启用</el-button>
            <el-button :disabled="!selected.length" @click="batchDisable">批量禁用</el-button>
            <el-button type="danger" :disabled="!selected.length" @click="batchDelete"
              >批量删除</el-button
            >
          </div>
          <el-table 
            :data="users" 
            v-loading="loading" 
            @selection-change="handleSelectionChange"
            :max-height="600"
            border
            stripe
            style="width: 100%; overflow-x: auto;"
          >
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column label="ID" prop="id" width="80" fixed="left" />
            <el-table-column label="头像" width="80">
              <template #default="{ row }">
                <el-avatar 
                  :size="40" 
                  :src="row.avatarUrl ? `http://localhost:8083${row.avatarUrl}` : undefined"
                  :icon="!row.avatarUrl ? 'UserFilled' : undefined"
                />
              </template>
            </el-table-column>
            <el-table-column label="用户名" prop="username" width="120" />
            <el-table-column label="昵称" prop="nickname" width="120" />
            <el-table-column label="真实姓名" prop="realName" width="120" />
            <el-table-column label="邮箱" prop="email" width="180" />
            <el-table-column label="手机号" prop="phone" width="130" />
            <el-table-column label="性别" width="80">
              <template #default="{ row }">
                <el-tag :type="row.gender === 1 ? 'primary' : row.gender === 2 ? 'success' : 'info'">
                  {{ row.gender === 1 ? '男' : row.gender === 2 ? '女' : '未知' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-switch
                  :model-value="row.status === 1"
                  @change="(val: string | number | boolean) => toggleStatus(row, !!val)"
                />
              </template>
            </el-table-column>
            <el-table-column label="注册时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="最后登录" width="160">
              <template #default="{ row }">
                {{ row.lastLoginAt ? formatDateTime(row.lastLoginAt) : '从未登录' }}
              </template>
            </el-table-column>
            <el-table-column label="生日" width="120">
              <template #default="{ row }">
                {{ row.birthday ? formatDate(row.birthday) : '未设置' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="openEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteUserRow(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pager">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-size="pageSize"
              :current-page="page"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
  <!-- 编辑用户对话框 -->
  <el-dialog
    :model-value="dialogVisible"
    title="编辑用户"
    width="600px"
    @close="dialogVisible = false"
  >
    <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="form.nickname" placeholder="请输入昵称" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="form.realName" placeholder="请输入真实姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
              <el-option label="未知" :value="0" />
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="form.birthday"
              type="date"
              placeholder="请选择生日"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="禁用" :value="0" />
              <el-option label="启用" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="头像" prop="avatarUrl">
        <el-input v-model="form.avatarUrl" placeholder="请输入头像URL" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveUser">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userService } from '@/api/userService'
import { extractErrorMessage } from '@/utils/errorHandler'
import type { User, ApiResponse, PageInfo } from '@/types'

const loading = ref(false)
const users = ref<User[]>([])
const selected = ref<User[]>([])
const dialogVisible = ref(false)
const form = ref<Partial<User>>({})
const editingId = ref<number | null>(null)
const formRef = ref()
// 分页相关状态
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const keyword = ref('')

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email' as const, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 20, message: '昵称长度在 1 到 20 个字符', trigger: 'blur' }
  ]
}

const loadUsers = async () => {
  loading.value = true
  try {
    const res = await userService.getUsersListPage(page.value, pageSize.value, {
      keyword: keyword.value || undefined,
      status: undefined,
      gender: undefined
    })
    const body = res.data as ApiResponse<PageInfo<User>>
    if (body.code === 200) {
      const data = body.data
      if (data) {
        users.value = data.list || []
        total.value = data.total || 0
      }
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

const openEdit = (user: User) => {
  editingId.value = user.id
  form.value = {
    id: user.id,
    username: user.username,
    nickname: user.nickname,
    email: user.email,
    phone: user.phone,
    avatarUrl: user.avatarUrl,
    realName: user.realName,
    gender: user.gender,
    birthday: user.birthday ? parseBackendDate(user.birthday) : undefined,
    status: user.status
  }
  dialogVisible.value = true
}

const deleteUserRow = async (row: User) => {
  try {
    await userService.deleteUser(row.id)
    await loadUsers()
  } catch (e) {
    console.error('删除用户失败', e)
  }
}

const toggleStatus = async (row: User, val: boolean) => {
  try {
    await userService.toggleUserStatus(row.id, val ? 1 : 0)
    await loadUsers()
  } catch (e) {
    console.error('切换用户状态失败', e)
  }
}

const handleSelectionChange = (rows: User[]) => {
  selected.value = rows
}

const batchEnable = async () => {
  if (!selected.value.length) return
  await Promise.all(selected.value.map((u) => userService.toggleUserStatus(u.id, 1)))
  selected.value = []
  await loadUsers()
}

const batchDisable = async () => {
  if (!selected.value.length) return
  await Promise.all(selected.value.map((u) => userService.toggleUserStatus(u.id, 0)))
  selected.value = []
  await loadUsers()
}

const batchDelete = async () => {
  if (!selected.value.length) return
  await Promise.all(selected.value.map((u) => userService.deleteUser(u.id)))
  selected.value = []
  await loadUsers()
}

onMounted(() => {
  loadUsers()
})

const saveUser = async () => {
  if (!editingId.value) return
  
  try {
    // 表单验证
    await formRef.value?.validate()
    
    // 准备要保存的数据，转换日期格式
    const saveData = {
      ...form.value,
      birthday: formatDateForBackend(form.value.birthday)
    }
    
    // 保存用户信息
    await userService.updateUser(saveData as Partial<User>)
    dialogVisible.value = false
    await loadUsers()
    
    // 显示成功消息
    ElMessage.success('用户信息更新成功')
  } catch (error: unknown) {
    console.error('更新用户失败:', error)
    const errorMessage = extractErrorMessage(error, '更新失败')
    ElMessage.error(errorMessage)
  }
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化日期（仅日期部分）
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 处理后端LocalDate格式，转换为前端可用的日期格式
const parseBackendDate = (dateString: string | null): string => {
  if (!dateString) return ''
  // 后端LocalDate格式通常是 "YYYY-MM-DD"，需要转换为ISO格式
  // 添加时间部分，设置为当天的00:00:00
  const date = new Date(dateString + 'T00:00:00')
  return date.toISOString().split('T')[0]
}

// 将前端日期转换为后端LocalDate格式
const formatDateForBackend = (dateString: string | undefined | null): string | null => {
  if (!dateString) return null
  // 确保日期格式为 YYYY-MM-DD
  const date = new Date(dateString)
  return date.toISOString().split('T')[0]
}

// 分页处理函数
const handlePageChange = (p: number) => {
  page.value = p
  loadUsers()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  page.value = 1 // 切换每页数量时重置到第一页
  loadUsers()
}
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
}
.toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 10px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

/* 表格横向滚动样式 */
.el-table {
  overflow-x: auto;
}

.el-table__body-wrapper {
  overflow-x: auto;
}

/* 确保表格容器可以横向滚动 */
.table-container {
  overflow-x: auto;
  width: 100%;
}
</style>
